import backend from "app/backend";
import message from "app/messages";
import { getUrlVars , getToken} from "app/utils.js"

let query=getUrlVars();
let token=query.token;
document.title=decodeURIComponent(query.title);
let myUID;
let convDoms={};

var getMsgTime = function (time) {
    var msgTime = new Date(time);
    var nowTime = new Date();

    var diffVal = nowTime - msgTime;
    if (diffVal <= 0) return '未来'; //虽然不知道为什么会有这种数据

    var _seconds = 1000;
    var _minutes = _seconds * 60;
    var _hours = _minutes * 60;
    var _date = _hours * 24;
    var _moth = _date * 30; //相对时间以30天为一个月
    var _year = _moth * 12;

    if (diffVal / _year > 1) return Math.floor(diffVal / _year) + '年前';
    if (diffVal / _moth > 1) return Math.floor(diffVal / _moth) + '个月前';
    if (diffVal / _date > 1) return Math.floor(diffVal / _date) + '天前';
    if (diffVal / _hours > 1) return Math.floor(diffVal / _hours) + '小时前';
    if (diffVal / _minutes > 1) return Math.floor(diffVal / _minutes) + '分钟前';

    return '刚才';
};

async function init() {
    await message.init(token);
    myUID=await backend.tokenify(getToken());
    await message.listConversations();
    if (message.conversationOrder) {
        for (let otherParty of message.conversationOrder) {
            let user = await backend.user.get(otherParty);
            let msgs = message.conversations[otherParty].messages;
            msgs[msgs.length - 1].time = getMsgTime(msgs[msgs.length - 1].time);
            let dom = $(conversation({user, message: msgs[msgs.length - 1]}));
            convDoms[otherParty] = dom;
            $("#container").append(dom);
        }
    }
    message.addMessageHandler(async(msg) => {
        let otherParty = myUID == msg.from ? msg.to : msg.from;
        let user = await backend.user.get(otherParty);
        msg.time = getMsgTime(msg.time);
        let dom = $(conversation({user, message: msg, token, unread:message.conversations[otherParty].unread}));
        if (convDoms[otherParty])
            convDoms[otherParty].remove();
        convDoms[otherParty] = dom;
        $("#container").prepend(dom);
    });
}
init();

$(function () {
    $('.msg-body').css('height', ($(document).height() - 140) + 'px');
    $('.msg-btn-close').click(function (e) {
        $(this).parents('.msg-box').animate({
            left: $(document).width() + 'px',
        }, 300, 'swing', function () {
            $(this).hide();
        });
    });
    $('.contact-box li').click(function () {
        var contactId = $(this).data('contact');
        $('.msg-box[data-contact=' + contactId + ']').show().animate({
            left: '0px',
        }, 300, 'swing');
    });
});

